################################################################################
##  Replication Code from "Do Conspiracy Theories Undermine Support for 
##  Democracy? Experimental Evidence from Brazil" 
################################################################################

# This code:
# 1. Tests main hypotheses
# 2. Creates and exports coefficient plots from the Main Paper (Figures 1, 2, 3, and 4)
# 3. Presents full regression models available at the appendix (Tables A27 to A33)

library(tidyverse)
library(haven)
library(sjlabelled)
library(psych)
library(sjPlot)
library(Hmisc)
library(lavaan)
library(broom)
library(stargazer)
library(modelsummary)
library(xtable)

# Data --------------------------------------------------------------------

setwd("C:/Users/vanes/Downloads")

## Study 1 data
df1 <- read.csv("./Study 1_clean_pca outcomes.csv")

## Study 2 data
df2 <- read.csv("./Study 2_clean_pca outcomes.csv")

## Changes reference level of the experimental group variable
df1$exp_group <- factor(df1$exp_group, levels = c("Placebo",
                                                  "Oficial",
                                                  "Maçonaria",
                                                  "Esquerda",
                                                  "Direita"))

## Selects relevant columns
outcomes.1 <- df1[, c(60:67, 72, 73)]

## Renames outcomes
names(outcomes.1) <- c("Accept election results",
                       "Candidates should accept election results",
                       "Support for strongmen",
                       "Undue political influence",
                       "Ban protests",
                       "Ban government critics",
                       "Electoral violence",
                       "Support for democracy",
                       "Aggression bolsonaristas",
                       "Aggresion lulistas")

# ------------------------------------------------------------------------------
# Models 
# ------------------------------------------------------------------------------

# Hypothesis 1: Support for democracy -------------------------------------

df1$dem_index <- df1$dem_index / 10

h1_placebo <- lm(data = df1,
                 scale(dem_index) ~ CTxPlacebo)

h1_official <- lm(data = df1,
                  scale(dem_index) ~ XCTxOficial)

# Models with separate items (Placebo baseline)
h1_pi   <- lm(scale(election_results) ~ CTxPlacebo, data = df1)
h1_pii  <- lm(scale(checks_bal)      ~ CTxPlacebo, data = df1)
h1_piii <- lm(scale(civil_lib)       ~ CTxPlacebo, data = df1)
h1_piv  <- lm(scale(violence_index)  ~ CTxPlacebo, data = df1)
h1_pv   <- lm(scale(sup_dem)         ~ CTxPlacebo, data = df1)

# Models with separate items (Official theory baseline)
h1_oi   <- lm(scale(election_results) ~ XCTxOficial, data = df1)
h1_oii  <- lm(scale(checks_bal)      ~ XCTxOficial, data = df1)
h1_oiii <- lm(scale(civil_lib)       ~ XCTxOficial, data = df1)
h1_oiv  <- lm(scale(violence_index)  ~ XCTxOficial, data = df1)
h1_ov   <- lm(scale(sup_dem)         ~ XCTxOficial, data = df1)

# Hypothesis 2: Institutional trust ---------------------------------------

h2.placebo <- lm(data = df2,
                 scale(institutional_trust) ~ CTxPlacebo)

h2.official <- lm(data = df2,
                  scale(institutional_trust) ~ CTxOficial)

h2_groups <- lm(scale(institutional_trust) ~ exp_arm, df2)

h2.elec.placebo <- lm(scale(electoral_trust) ~ CTxPlacebo, data = df2)
h2.elec.official <- lm(scale(electoral_trust) ~ CTxOficial, data = df2)

h2.elec.1.placebo <- lm(scale(Q.trust_eleições) ~ CTxPlacebo, data = df2)
h2.elec.2.placebo <- lm(scale(Q.invasão)        ~ CTxPlacebo, data = df2)
h2.elec.3.placebo <- lm(scale(Q.aceitação1)     ~ CTxPlacebo, data = df2)

h2.elec.1.official <- lm(scale(Q.trust_eleições) ~ CTxOficial, data = df2)
h2.elec.2.official <- lm(scale(Q.invasão)        ~ CTxOficial, data = df2)
h2.elec.3.official <- lm(scale(Q.aceitação1)     ~ CTxOficial, data = df2)

# Hypothesis 3: Partisan hostility ----------------------------------------

h3.placebo <- lm(data = df2,
                 scale(partisan_hostility) ~ CTxPlacebo)

h3.official <- lm(data = df2,
                  scale(partisan_hostility) ~ CTxOficial)

# Hostility -- individual items 
h3.1 <- lm(data = df2, extr.outgroup    ~ CTxOficial)
h3.2 <- lm(data = df2, dehum.outgroup   ~ CTxOficial)
h3.3 <- lm(data = df2, Q.identidade_imp ~ CTxOficial)
h3.4 <- lm(data = df2, Q.aceitação2     ~ CTxOficial)

# ------------------------------------------------------------------------------
# Prepping for figures 
# ------------------------------------------------------------------------------

# Transforms models to tidy format ----------------------------------------

# H1 models
h11.p.td <- tidy(h1_placebo) %>%
  mutate(outcome = "OSDI",
         Baseline = "Placebo")

h11.o.td <- tidy(h1_official) %>%
  mutate(outcome = "OSDI",
         Baseline = "Official Theory")

# H2 models
h2.p.td <- tidy(h2.placebo) %>%
  mutate(outcome = "Institutional Trust",
         Baseline = "Placebo")

h2.o.td <- tidy(h2.official) %>%
  mutate(outcome = "Institutional Trust",
         Baseline = "Official Theory")

# H2 models (electoral trust)
h2.elec.p.td <- tidy(h2.elec.placebo) %>%
  mutate(outcome = "Electoral Trust Index",
         Baseline = "Placebo")

h2.elec.o.td <- tidy(h2.elec.official) %>%
  mutate(outcome = "Electoral Trust Index",
         Baseline = "Official Theory")

# H2 disaggregated outcomes
h2.elec.1.p.td <- tidy(h2.elec.1.placebo) %>%
  mutate(outcome = "Trust 2022 Elections",
         Baseline = "Placebo")

h2.elec.2.p.td <- tidy(h2.elec.2.placebo) %>%
  mutate(outcome = "Condemn Jan 08",
         Baseline = "Placebo")

h2.elec.3.p.td <- tidy(h2.elec.3.placebo) %>%
  mutate(outcome = "Candidates Should Accept",
         Baseline = "Placebo")

h2.elec.1.o.td <- tidy(h2.elec.1.official) %>%
  mutate(outcome = "Trust 2022 Elections",
         Baseline = "Official Theory")

h2.elec.2.o.td <- tidy(h2.elec.2.official) %>%
  mutate(outcome = "Condemn Jan 08",
         Baseline = "Official Theory")

h2.elec.3.o.td <- tidy(h2.elec.3.official) %>%
  mutate(outcome = "Candidates Should Accept",
         Baseline = "Official Theory")

# H3 models
h3.p.td <- tidy(h3.placebo) %>%
  mutate(outcome = "Partisan Hostility",
         Baseline = "Placebo")

h3.o.td <- tidy(h3.official) %>%
  mutate(outcome = "Partisan Hostility",
         Baseline = "Official Theory")

# Appending models into a dataframe ---------------------------------------

models <- bind_rows(
  h11.p.td, h11.o.td,
  h2.p.td,  h2.o.td,
  h2.elec.p.td, h2.elec.o.td,
  h2.elec.1.p.td, h2.elec.2.p.td, h2.elec.3.p.td,
  h2.elec.1.o.td, h2.elec.2.o.td, h2.elec.3.o.td,
  h3.p.td, h3.o.td
) %>%
  filter(term != "(Intercept)")

models$Baseline <- factor(models$Baseline,
                          levels = c("Placebo", "Official Theory"))

models$outcome <- factor(models$outcome,
                         levels = c("OSDI",
                                    "Institutional Trust",
                                    "Partisan Hostility",
                                    "Trust 2022 Elections",
                                    "Condemn Jan 08",
                                    "Candidates Should Accept",
                                    "Electoral Trust Index"))

models$term <- models$Baseline

# Transforms models with separate outcomes to tidy format -----------------

h1.pi.td <- tidy(h1_pi) %>%
  mutate(outcome = "Election Results",
         Baseline = "Placebo")

h1.pii.td <- tidy(h1_pii) %>%
  mutate(outcome = "Checks and Balances",
         Baseline = "Placebo")

h1.piii.td <- tidy(h1_piii) %>%
  mutate(outcome = "Civil Liberties",
         Baseline = "Placebo")

h1.piv.td <- tidy(h1_piv) %>%
  mutate(outcome = "Electoral Violence",
         Baseline = "Placebo")

h1.pv.td <- tidy(h1_pv) %>%
  mutate(outcome = "Support for Democracy",
         Baseline = "Placebo")

h1.oi.td <- tidy(h1_oi) %>%
  mutate(outcome = "Election Results",
         Baseline = "Official Theory")

h1.oii.td <- tidy(h1_oii) %>%
  mutate(outcome = "Checks and Balances",
         Baseline = "Official Theory")

h1.oiii.td <- tidy(h1_oiii) %>%
  mutate(outcome = "Civil Liberties",
         Baseline = "Official Theory")

h1.oiv.td <- tidy(h1_oiv) %>%
  mutate(outcome = "Electoral Violence",
         Baseline = "Official Theory")

h1.ov.td <- tidy(h1_ov) %>%
  mutate(outcome = "Support for Democracy",
         Baseline = "Official Theory")

models2 <- bind_rows(
  h1.pi.td, h1.pii.td, h1.piii.td, h1.piv.td, h1.pv.td,
  h1.oi.td, h1.oii.td, h1.oiii.td, h1.oiv.td, h1.ov.td
) %>%
  filter(term != "(Intercept)")

models2$Baseline <- factor(models2$Baseline,
                           levels = c("Placebo", "Official Theory"))
models2$term <- models2$Baseline

# ------------------------------------------------------------------------------
# Figure 1 (Hypotheses 1, 2 and 3)
# ------------------------------------------------------------------------------

models$term <- factor(
  models$term,
  levels = c("Official Theory", "Placebo")
)

results.graph <- ggplot(
  models %>%
    filter(outcome %in% c("OSDI", "Institutional Trust", "Partisan Hostility")),
  aes(x = term, y = estimate, color = term)
) +
  geom_point(
    position = position_dodge(0.5),
    size = 1.75
  ) +
  geom_errorbar(
    aes(ymin = estimate - 1.96 * std.error,
        ymax = estimate + 1.96 * std.error),
    width = 0,
    position = position_dodge(0.3)
  ) +
  geom_errorbar(
    aes(ymin = estimate - 1.65 * std.error,
        ymax = estimate + 1.65 * std.error),
    width = 0,
    position = position_dodge(0.3),
    size = 1.25
  ) +
  geom_hline(yintercept = 0, linetype = 2, color = "grey60") +
  scale_color_manual(
    values = c(
      "Official Theory" = "#F8766D",
      "Placebo" = "#00BFC4"
    )
  ) +
  labs(
    x = "Baseline",
    y = "Standardized Coefficients",
    color = "Baseline"
  ) +
  theme_bw() +
  theme(legend.position = "none")+
  theme(panel.grid = element_blank()) +
  facet_wrap(~outcome)

results.graph

ggsave("./study 2_main results.png", results.graph, "png", width = 7, height = 3.5)

# Tables for Figure 1 (A27–A29) -------------------------------------------

stargazer(
  h1_placebo,
  h1_official,
  type = "latex",
  title = "Effects on OSDI (H1)",
  dep.var.labels = "Scaled Democracy Index",
  covariate.labels = c("CTxPlacebo", "XCTxOficial"),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "h1_regressions_stargazer.tex"
)

stargazer(
  h2.placebo,
  h2.official,
  type = "latex",
  title = "Effects on Institutional Trust (H2)",
  dep.var.labels = "Institutional Trust",
  covariate.labels = c("CTxPlacebo", "CTxOficial"),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "h2_regressions_stargazer.tex"
)

stargazer(
  h3.placebo,
  h3.official,
  type = "latex",
  title = "Effects on Partisan Hostility",
  dep.var.labels = "Partisan Hostility",
  covariate.labels = c("CTxPlacebo", "CTxOficial"),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "h3_regressions_stargazer.tex"
)

# ------------------------------------------------------------------------------
# Figure 2
# ------------------------------------------------------------------------------

h1.outcomes.graph <- ggplot(
  models2,
  aes(x = outcome, y = estimate, color = term)
) +
  geom_point(position = position_dodge(0.3), size = 2.5) +
  geom_errorbar(aes(ymin = estimate - 1.96 * std.error,
                    ymax = estimate + 1.96 * std.error),
                width = 0, position = position_dodge(0.3)) +
  geom_errorbar(aes(ymin = estimate - 1.65 * std.error,
                    ymax = estimate + 1.65 * std.error),
                width = 0, position = position_dodge(0.3), size = 1.25) +
  geom_hline(yintercept = 0, linetype = 2, color = "grey60") +
  labs(x = "Outcomes", y = "Standardized Coefficients", color = "Baseline") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        legend.position = "bottom")

h1.outcomes.graph

ggsave("../h1_outcomes_graph.png", h1.outcomes.graph, "png", width = 8, height = 3.5)

# Tables for Figure 2 (A31–A32) -------------------------------------------

stargazer(
  h1_pi, h1_pii, h1_piii, h1_piv, h1_pv,
  type = "latex",
  title = "Regression Results: Placebo Baseline",
  dep.var.labels = c(
    "Election Results", "Checks & Balances",
    "Civil Liberties", "Violence Index",
    "Support for Democracy"
  ),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "regressions_placebo.tex"
)

stargazer(
  h1_oi, h1_oii, h1_oiii, h1_oiv, h1_ov,
  type = "latex",
  title = "Regression Results: Official Theory Baseline",
  dep.var.labels = c(
    "Election Results", "Checks & Balances",
    "Civil Liberties", "Violence Index",
    "Support for Democracy"
  ),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "regressions_official.tex"
)

# ------------------------------------------------------------------------------
# Figure 3
# ------------------------------------------------------------------------------

models$term <- factor(
  models$term,
  levels = c("Official Theory", "Placebo")
)

results.elections <- ggplot(
  models %>%
    filter(outcome %in% c("Trust 2022 Elections",
                          "Condemn Jan 08",
                          "Candidates Should Accept",
                          "Electoral Trust Index")),
  aes(x = term, y = estimate, color = term)
) +
  geom_point(position = position_dodge(0.5), size = 1.75) +
  geom_errorbar(
    aes(ymin = estimate - 1.96 * std.error,
        ymax = estimate + 1.96 * std.error),
    width = 0,
    position = position_dodge(0.3)
  ) +
  geom_errorbar(
    aes(ymin = estimate - 1.65 * std.error,
        ymax = estimate + 1.65 * std.error),
    width = 0,
    position = position_dodge(0.3),
    size = 1.25
  ) +
  geom_hline(yintercept = 0, linetype = 2, color = "grey60") +
  scale_color_manual(
    values = c(
      "Placebo" = "#F8766D",
      "Official Theory" = "#00BFC4"
    )
  ) +
  labs(
    x = "Baseline",
    y = "Standardized Coefficients"
  ) +
  theme_bw() +
  theme(
    panel.grid = element_blank(),
    legend.position = "none"
  ) +
  facet_wrap(~outcome, nrow = 1)

results.elections

ggsave("./study 2_election results.png", results.elections, "png", width = 9, height = 3.5)

### additional outcomes related to support for democracy included in study 2

## Placebo as baseline

# Table A32 ------------------------------------------------

m_elec_trust   <- h2.elec.1.placebo
m_jan08        <- h2.elec.2.placebo
m_accept       <- h2.elec.3.placebo
m_elec_index   <- h2.elec.placebo

stargazer(
  m_elec_trust, m_jan08, m_accept, m_elec_index,
  type = "latex",
  title = "Additional Results Study 2: Placebo Baseline",
  dep.var.labels = c("Trust 2022 Elections", "Condemn Jan 08",
                     "Candidates Should Accept", "Electoral Trust Index"),
  star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
  star.char = c("+", "*", "**", "***"),
  omit.stat = c("f", "ser", "adj.rsq"),
  notes = c("*** p<0.001", "** p<0.01", "* p<0.05", "+ p<0.1"),
  notes.append = FALSE,
  out = "regressions_study2_placebo.tex"
)

# ------------------------------------------------------------------------------
# Figure 4 (H4) 
# ------------------------------------------------------------------------------

## heterogeneous effect by partisanship

# hypothesis 3 -- political trust
summary(
  h1.int.placebo <- lm(scale(trust.pca) ~ CTxPlacebo,
                       df2 %>% filter(partisan == 1))
)

summary(
  h1.int.official <- lm(scale(trust.pca) ~ CTxOficial*partisan,
                        df2)
)

### the model above shows that CTs decrease trust especially among non-partisans

bind_rows(
  tidy(
    lm(data = df1 %>% filter(partisan == 1),
       scale(dem_index) ~ XCTxOficial)) %>%
    mutate(Baseline = "Official Theory",
           Outcome = "OSDI",
           Group = "Partisans") %>%
    
    bind_rows(
      tidy(
        lm(data = df1 %>% filter(partisan == 1),
           scale(dem_index) ~ CTxPlacebo)) %>% 
        mutate(Baseline = "Placebo",
               Outcome = "OSDI",
               Group = "Partisans") %>%
        
        bind_rows(
          tidy(
            lm(data = df1 %>% filter(partisan == 0),
               scale(dem_index) ~ XCTxOficial)) %>%
            mutate(Baseline = "Official Theory",
                   Outcome = "OSDI",
                   Group = "Non-Partisans") %>%
            bind_rows(
              tidy(
                lm(data = df1 %>% filter(partisan == 0),
                   scale(dem_index) ~ CTxPlacebo)) %>%
                mutate(Baseline = "Placebo",
                       Outcome = "OSDI",
                       Group = "Non-Partisans")))),
  tidy(
    lm(scale(institutional_trust) ~ CTxPlacebo,
       df2 %>% filter(partisan == 1))
  ) %>% 
    mutate(Baseline = "Placebo",
           Outcome = "Institutional Trust",
           Group = "Partisans"),
  
  tidy(
    lm(scale(institutional_trust) ~ CTxPlacebo,
       df2 %>% filter(partisan == 0))
  ) %>% 
    mutate(Baseline = "Placebo",
           Outcome = "Institutional Trust",
           Group = "Non-Partisans"),
  
  tidy(
    lm(scale(institutional_trust) ~ CTxOficial,
       df2 %>% filter(partisan == 1))
  ) %>% 
    mutate(Baseline = "Official Theory",
           Outcome = "Institutional Trust",
           Group = "Partisans"),
  
  tidy(
    lm(scale(institutional_trust) ~ CTxOficial,
       df2 %>% filter(partisan == 0))
  ) %>% 
    mutate(Baseline = "Official Theory",
           Outcome = "Institutional Trust",
           Group = "Non-Partisans"),
  
  # hypothesis 3 -- political conflict
  tidy(
    lm(scale(partisan_hostility) ~ CTxPlacebo,
       df2 %>% filter(partisan == 1))
  ) %>% 
    mutate(Baseline = "Placebo",
           Outcome = "Partisan Hostility",
           Group = "Partisans"),
  
  tidy(
    lm(scale(partisan_hostility) ~ CTxPlacebo,
       df2 %>% filter(partisan == 0))
  ) %>% 
    mutate(Baseline = "Placebo",
           Outcome = "Partisan Hostility",
           Group = "Non-Partisans"),
  
  tidy(
    lm(scale(partisan_hostility) ~ CTxOficial,
       df2 %>% filter(partisan == 1))
  ) %>% 
    mutate(Baseline = "Official Theory",
           Outcome = "Partisan Hostility",
           Group = "Partisans"),
  
  tidy(
    lm(scale(partisan_hostility) ~ CTxOficial,
       df2 %>% filter(partisan == 0))
  ) %>% 
    mutate(Baseline = "Official Theory",
           Outcome = "Partisan Hostility",
           Group = "Non-Partisans"),
  
) %>%
  mutate(Outcome = factor(Outcome, levels = c("OSDI" ,"Institutional Trust", "Partisan Hostility")),
         Baseline = factor(Baseline, levels = c("Placebo", "Official Theory"))) %>%
  filter(term != "(Intercept)") %>%
  ggplot(aes(x = Baseline, y = estimate, color = Group)) +
  geom_point(position = position_dodge(0.5), size = 1.75) +
  geom_errorbar(aes(ymin = estimate - 1.96*std.error, ymax = estimate + 1.96*std.error), 
                width = 0, position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = estimate - 1.65*std.error, ymax = estimate + 1.65*std.error), 
                width = 0, position = position_dodge(0.5), size = 1.25) +
  geom_hline(yintercept = 0, linetype = 2, color = "grey60") +
  labs(x = "Baseline", y = "Standardized Coefficients", color = "") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        legend.position = "bottom") +
  facet_wrap(~Outcome) -> study2.partisan

study2.partisan

### Exports graph
ggsave("./study2_outcomes_partisan.png", study2.partisan, "png", width = 6, height = 3.75)


# Table for Figure 4 (A33) ------------------------------------------------

run_model <- function(formula, data, baseline, group) {
  tidy(lm(formula, data = data)) %>%
    filter(term != "(Intercept)") %>%
    mutate(
      Baseline = baseline,
      Outcome = "OSDI",
      Group = group
    ) %>%
    select(Baseline, Group, Outcome, term, estimate, std.error, statistic, p.value)
}

m1 <- run_model(scale(dem_index) ~ XCTxOficial,
                df1 %>% filter(partisan == 1),
                "Official Theory", "Partisans")

m2 <- run_model(scale(dem_index) ~ CTxPlacebo,
                df1 %>% filter(partisan == 1),
                "Placebo", "Partisans")

m3 <- run_model(scale(dem_index) ~ XCTxOficial,
                df1 %>% filter(partisan == 0),
                "Official Theory", "Non-Partisans")

m4 <- run_model(scale(dem_index) ~ CTxPlacebo,
                df1 %>% filter(partisan == 0),
                "Placebo", "Non-Partisans")

tabela_final <- bind_rows(m1, m2, m3, m4) %>%
  mutate(
    estimate = round(estimate, 3),
    std.error = round(std.error, 3),
    statistic = round(statistic, 2),
    p.value = round(p.value, 3)
  )

print(
  xtable(
    tabela_final,
    caption = "Effects of Treatments on OSDI (Standardized Coefficients)",
    label = "tab:osdi_partisanship"
  ),
  include.rownames = FALSE,
  booktabs = TRUE,
  caption.placement = "top"
)
######################
